import Vue from "vue"
import router from '@/router'
import { Message } from 'element-ui'
import screenfull from 'screenfull'
import Color from 'color'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { chartColors } from '@/settings'
NProgress.configure({
  showSpinner: false
})
/**
 * * 获取图片内容
 * @param {ConfigType} targetData 配置项
 */
export const fetchImages = async (targetData) => {
  if (!targetData) return ''
  // 正则判断图片是否为 url，是则直接返回该 url
  if (/^(http|https):\/\/([\w.]+\/?)\S*/.test(targetData.image)) return targetData.image
  // 新数据动态处理
  const { image } = targetData
  const imageName = image.substring(image.lastIndexOf('/') + 1)
  let packag = targetData.package.charAt(0).toLowerCase() + targetData.package.slice(1)
  let img = require(`@/assets/images/chart/${packag}/${image}`)
  return img
}

/**
 * * 全屏操作函数
 * @param isFullscreen
 * @param isEnabled
 * @returns
 */
export const screenfullFn = (isFullscreen, isEnabled) => {
  // 是否是全屏
  if (isFullscreen) return screenfull.isFullscreen

  // 是否支持全屏
  if (isEnabled) return screenfull.isEnabled

  if (screenfull.isEnabled) {
    screenfull.toggle()
    return
  }
  Message.warning('您的浏览器不支持全屏功能！')
}

/**
 * * 动态注册组件
 */
export const componentInstall = (key, node) => {
  if (!Vue.component[key] && node) {
    Vue.component(key, node)
  }
}

/**
 * * 生成一个不重复的ID
 * @param { Number } randomLength
 */
export const getUUID = (randomLength = 10) => {
  return Number(Math.random().toString().substring(2, randomLength) + Date.now()).toString(36)
}

export function isString (p) {
  return typeof p === 'string'
}

export function isArray (p) {
  return Array.isArray(p)
}

// * 开启加载
export const loadingStart = () => {
  NProgress.start()
}

// * 加载结束
export const loadingFinish = () => {
  setTimeout(() => {
    NProgress.done()
  })
}

// * 滤镜
export const getFilterStyle = (styles) => {
  if (!styles || !styles.filterShow) return {}
  const { opacity, saturate, contrast, hueRotate, brightness } = styles
  return {
    opacity: opacity,
    filter: `saturate(${saturate}) contrast(${contrast}) hue-rotate(${hueRotate}deg) brightness(${brightness})`
  }
}

// * 变换
export const getTransformStyle = (styles) => {
  const { rotateZ, rotateX, rotateY, skewX, skewY } = styles
  return {
    transform: `rotateZ(${rotateZ || 0}deg) rotateX(${rotateX || 0}deg) rotateY(${rotateY || 0}deg) skewX(${skewX || 0
      }deg) skewY(${skewY || 0}deg)`
  }
}

// * 动画
export const animationsClass = (animations) => {
  if (animations.length) {
    return `animate__animated  animate__${animations[0]}`
  }
  return ''
}

/**
 * * 合并基础颜色和自定义颜色
 * @param chartDefaultColors
 * @param customColor
 * @returns
 */
export const colorCustomMerge = (customColor) => {
  const formateCustomColor = {}
  customColor?.forEach(item => {
    formateCustomColor[item.id] = {
      color: item.color,
      name: item.name
    }
  })
  return { ...formateCustomColor, ...chartColors }
}

/**
 * * 获取本地会话数据
 * @param k 键名
 * @returns any
 */
export const getLocalStorage = (k) => {
  const item = localStorage.getItem(k)
  try {
    return item ? JSON.parse(item) : item
  } catch (err) {
    return item
  }
}

// * 混合模式
export const getBlendModeStyle = (styles) => {
  if (!styles || !styles.filterShow) return {}
  const { blendMode } = styles
  return {
    'mix-blend-mode': blendMode
  }
}

/**
 * 修改元素位置
 * @param target 对象
 * @param x X轴
 * @param y Y轴
 */
export const setComponentPosition = (
  target,
  x,
  y
) => {
  x && (target.attr.x = x)
  y && (target.attr.y = y)
}

/**
 * * 根据名称获取路由信息
 * @param pageName
 * @param pageName
 */
export const fetchPathByName = (pageName, p) => {
  try {
    const pathData = router.resolve({
      name: pageName,
    })
    return p ? pathData[p] : pathData
  } catch (error) {
    Message.warning('查询路由信息失败，请联系管理员！')
  }
}

/**
 * * JSON序列化，支持函数和 undefined
 * @param data
 */
export const JSONStringify = data => {
  return JSON.stringify(
    data,
    (key, val) => {
      // 处理函数丢失问题
      if (typeof val === 'function') {
        return `${val}`
      }
      // 处理 undefined 丢失问题
      if (typeof val === 'undefined') {
        return null
      }
      return val
    },
    2
  )
}

/**
 * * 判断是否是预览页
 * @returns boolean
 */
export const isPreview = () => {
  return document.location.hash.includes('preview')
}


/**
 * * hsla 转换
 * @param color 颜色
 * @param alpha 默认1
 * @returns
 */
export function alpha (color, alpha = 1) {
  return Color(color).alpha(alpha).toString()
}

// 下载文件
export function downloadFile (url, fileName) {
  const a = document.createElement('a') // 创建下载链接
  a.download = fileName
  a.style.display = 'none' // 隐藏的可下载链接
  // 字符内容转变成blob地址
  a.href = url
  // 绑定点击时间
  document.body.appendChild(a)
  a.click()
  // 然后移除
  document.body.removeChild(a)
}

/**
 * *获取上传的文件数据
 * @param { File } file 文件对象
 */
export const readFile = (file) => {
  return new Promise((resolve) => {
    try {
      const reader = new FileReader()
      reader.onload = (evt) => {
        if (evt.target) {
          resolve(evt.target.result)
        }
      }
      reader.readAsText(file)
    } catch (error) {
      this.$message.error('文件读取失败！')
    }
  })
}

